// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.tcmdb.dao.mongo;


import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.query.Criteria;

import de.servicezombie.lang.WrappedException;

public class ToCriteriaTransformer {

	public Criteria transform(Object parameterBean) {
		
		Criteria query = new Criteria();		
		java.lang.reflect.Field[] fields = parameterBean.getClass().getDeclaredFields();
		
		try {
			for(java.lang.reflect.Field field : fields) {						
				appendCriteriaIfValueSet(query, field, parameterBean);			
			}
		}
		catch (IllegalArgumentException e) {
			throw new WrappedException(e);
		}
		catch (IllegalAccessException e) {
			throw new WrappedException(e);
		}
		
		return query;
		
	}

	private void appendCriteriaIfValueSet(Criteria criteria, java.lang.reflect.Field field, Object parameterBean) throws IllegalArgumentException, IllegalAccessException {
		
		field.setAccessible(true);
		Object value = field.get(parameterBean);
		
		if(value != null) {
			
			String name = field.getName();
			Field fieldAnnotation = field.getAnnotation(Field.class);
			
			if(fieldAnnotation != null && StringUtils.isNotBlank(fieldAnnotation.value())) {
				name = fieldAnnotation.value();
			}
			
			criteria.and(name).is(value);
		}		
	}
}
